package com.itheima.controller;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.itheima.entity.Result;
import com.itheima.service.OrderService;
import com.itheima.utils.PayUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
public class Paycontroller {

    @Reference
    private OrderService orderService;

    @RequestMapping("/orderPay.do")
    public Result goToPay(@RequestParam("oid") Integer oid){
            String orderId=orderService.findOrderIdById(oid);
        System.out.println("------"+orderId);
            String pay_url = PayUtils.createOrder(orderId, 1);
            System.out.println(pay_url);
            return new Result(true,"路径",pay_url);
            // 将数据设置到request域
            /*request.setAttribute("orderId", orderId);
            request.setAttribute("price", price);
            request.setAttribute("pay_url", pay_url);
            System.out.println("====================");
            request.getRequestDispatcher(request.getContextPath()+"/pages/pay.jsp").forward(request, response);*/



    }

    @RequestMapping("/payNotify.do")
    public void payNotify(HttpServletRequest request,HttpServletResponse response){
        try {
            // 1.接收请求参数（xml）
            ServletInputStream in = request.getInputStream();
            // 2.将xml转为java对象
            XmlMapper xmlMapper = new XmlMapper();
            Map param = xmlMapper.readValue(in, Map.class);
            // 3.调用orderService，修改订单状态
            orderService.updateState(param);
            System.out.println("================");
            // 4.返回微信平台，接收成功..
            HashMap<String, String> result = new HashMap<>();
            result.put("return_code", "SUCCESS");
            result.put("return_msg", "OK");
            // 将map转为xml
            String xml = xmlMapper.writeValueAsString(result);
            response.setContentType("application/xml;charset=utf-8");
            response.getWriter().write(xml);


        } catch (IOException e) {
            e.printStackTrace();

        }


    }

}
